package com.yufuchang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Objects;

/**
 * Created by yufuchang on 2020/9/7.
 */
@RestController
public class DownloadController {

    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/download")
    public void downLoadFile(){
// 记录下开始下载时的时间
        Instant now = Instant.now();
        // 待下载的文件地址
        String url = "https://app-store-test.oss.cn-north-3.inspurcloudoss.com/yunjia/2020-09-07/ccwork_V3.6.0_262_0_20200907_1437_sec_sign.apk";
        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url, byte[].class);
        System.out.println("状态码：" + rsp.getStatusCode());
        try {
//            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//            // 将下载下来的文件内容保存到本地
//            File upload = new File(path,"static/images/upload/");
//            if(!upload.exists()) upload.mkdirs();
            String targetPath = "D://Downloads/cloudplus.apk";
//            File uploadFile = new File(targetPath);
//            if(!uploadFile.exists()){
//                uploadFile.createNewFile();
//            }
            Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getBody(),
                    "未获取到下载文件"));
        } catch (Exception e) {
            System.out.println("文件写入失败：" + e.getMessage());
        }
        System.out.println("文件下载完成，耗时：" + ChronoUnit.MILLIS.between(now, Instant.now())
                + " 毫秒");
        return;
    }

    @GetMapping("/downloadBigFile")
    public void downloadBigFile(){
        // 记录下开始下载时的时间
        Instant now = Instant.now();
        // 待下载的文件地址
        String url = "https://app-store-test.oss.cn-north-3.inspurcloudoss.com/yunjia/2020-09-07/ccwork_V3.6.0_262_0_20200907_1437_sec_sign.apk";
        // 文件保存的本地路径
        String targetPath = "D://Downloads/cloudplus2.apk";
        File uploadFile = new File(targetPath);
        if(!uploadFile.exists()){
            try {
                uploadFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //定义请求头的接收类型
        RequestCallback requestCallback = request -> request.getHeaders()
                .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
        //对响应进行流式处理而不是将其全部加载到内存中
        restTemplate.execute(url, HttpMethod.GET, requestCallback, clientHttpResponse -> {
            Files.copy(clientHttpResponse.getBody(), Paths.get(targetPath));
            return null;
        });
        System.out.println("文件下载完成，耗时：" + ChronoUnit.MILLIS.between(now, Instant.now())
                + " 毫秒");
        return;
    }
}
